import os
import base64
from openai import OpenAI

# 定义方法将指定路径图片转为Base64编码


def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode('utf-8')


def ask_ai(file_path, question):
    base64_image = encode_image(file_path)
    # 初始化Ark客户端
    client = OpenAI(
        # 此为默认路径，您可根据业务所在地域进行配置
        base_url="https://ark.cn-beijing.volces.com/api/v3",
        # 使用直接设置的API Key
        api_key="0fdc3ea8-b90c-41e9-8a59-b61104479385"
    )

    response = client.chat.completions.create(
        # 指定您创建的方舟推理接入点 ID
        model="doubao-seed-1-6-vision-250815",
        stream=False,
        messages=[
            {
                "role": "system",
                "content": "你是一个专业的图像识别助手，能够识别图片中的常见对象并返回其位置和属性。"
            },
            {
                "role": "user",
                "content": [
                    {
                        "type": "image_url",
                        "image_url": {
                            # 修复图片格式占位符问题，使用实际的jpeg格式
                            "url": f"data:image/jpeg;base64,{base64_image}"
                        },
                    },
                    {"type": "text", "text": question},
                ],
            }
        ],
        extra_headers={'x-is-encrypted': 'false'},
        temperature=1,
        top_p=0.7,
        max_tokens=32768,
        extra_body={
            "thinking": {
                "type": "disabled"
            }}
    )

    print(f'提示词：: {question}')

    return response.choices[0].message.content


# 测试代码
""" file_path = "/Volumes/SSD_M2 1/tmp/upload/static/uploads/20250926044712_391b2568_converted.jpg"
res = ask_ai(
    file_path, '识别图片内容信息，返回json格式字符串。要求：1. 提取人、物品、汽车等常见对象。2. 位置是指该对象的顶部中心点，相对于左上角的x y坐标。3. 格式：[{"类别": "人"，"位置": "100,70","属性":“女人”},{"类别":"车","位置": "120,90","属性":“货车”]}
')

print(res) """
